package com.skyworth.web.api;

import com.skyworth.web.common.ApiResponse;
import com.skyworth.web.shiro.redis.RedisService;
import com.skyworth.web.admin.user.domain.UserModel;
import com.skyworth.web.admin.user.form.UserForm;
import com.skyworth.web.admin.user.service.UserService;
import com.skyworth.web.wechat.common.MD5Encode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


@RestController("apiSessionController")
public class SessionController {
    Logger LOG = LoggerFactory.getLogger(SessionController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;

    @RequestMapping(value = {"/api/login"}, method = RequestMethod.POST)
    public ApiResponse create(@RequestBody Map<String, Object> userMap, Model model) {

        UserForm userForm = new UserForm();
        userForm.username = userMap.get("username").toString();
        userForm.password = userMap.get("password").toString();
        ApiResponse apiResponse = new ApiResponse();
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userForm.username, MD5Encode.encode(userForm.password));
        try {
            currentUser.login(token);
            if (currentUser.isAuthenticated()) {
                apiResponse.setSuccess(true);
                apiResponse.setMessage("登录成功");

                UserModel user = userService.findUserByUsername(token.getUsername());
                apiResponse.setData(user);
            } else {
                apiResponse.setMessage("用户名或密码错误！");
            }
        } catch (UnknownAccountException ex) {//用户名没有找到
            apiResponse.setMessage("用户名或密码错误！");
        } catch (IncorrectCredentialsException ex) {//用户名密码不匹配
            apiResponse.setMessage("用户名或密码错误！");
        } catch (AuthenticationException e) {
            apiResponse.setMessage("服务器异常，请稍后再试！");
        }

        return apiResponse;
    }

    @RequestMapping(value = {"/api/logout"}, method = RequestMethod.GET)
    public String logout(Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "redirect:/login";
    }
}
